const Conn = require('./conn')
const querystring = require('querystring')
let sessionUser
let islogin
const apisCollect = {
    login (req,res) {
        let body = ''
        req.on('data', function(chunk){ 
            body += chunk
        })
        req.on('end', function(){ 
            body = querystring.parse(body)
            let sql = `select * from user`
            let conn = Conn() 
            conn.query(sql,(err,result)=>{
                if (err) {
                    res.end(JSON.stringify({status:0,msg:'登陆失败'}))
                }else{
                    if (result.length) {
                        req.session = {}
                        req.session.user = sessionUser = body.name
                        req.session.isLogin = islogin = true
                        res.end(JSON.stringify({status:1,msg:'登陆成功'}))
                    } else {
                      res.end(JSON.stringify({status:0,msg:'用户名或者密码不正确'}))
                    }
                }
            })
            conn.end()
        })
    }
}


module.exports = function(path,req,res) {
    let reqPath = path.split('/')
    reqPath = reqPath && reqPath.pop()
    console.log(reqPath, path)
    if (reqPath && apisCollect[reqPath]){
        apisCollect[reqPath](req, res)
    } else {
        res.writeHead(404, 'Not Found')
        res.end()
    }
}